HTML5 Games: Novice to Ninja by Earle Castledine

HTML5 Games: Novice to Ninja by Earle Castledine

Author:Earle Castledine [Earle Castledine]
Language: eng
Format: epub
Publisher: SitePoint Pty. Ltd.
Published: 2018-02-13T23:00:00+00:00


Normalizing, and the Dot Product

There are several additional operations that are frequently required when making games. One is the concept of normalizing a vector. Normalizing scales a vector so that its magnitude is exactly 1. To do this, take the current magnitude and divide each axis by that amount:

normalize() { const mag = this.mag(); if (mag > 0) { this.x /= mag; this.y /= mag; } return this; }

The result of normalizing is a unit vector (because it would touch the perimeter of a unit circle—a circle with radius 1). Normalizing gives us the essence of the direction of a vector. Once you have the essence, you can manipulate this in consistent ways. For example, a normalized vector can be rescaled to get a specific magnitude in the given direction. Here’s how to find the point exactly 50 pixels away from the player, in the direction the bad guy:

player.pos.clone() .add(badguys.pos) .normalize() .multiply(50)

The last operation we’ll look at is a weird one, but one that often appears in AI behaviors—the dot product. The dot product is the sums of the products of corresponding components. It’s calculated like this:

dot({x, y}) { return this.x * x + this.y * y; }

The result of the dot product is the x components multiplied together, plus the y components multiplied together—a scalar value. Intuitively, this might seem like a strange idea, but it has some interesting properties with regards to the angle between the two vectors.

When two vectors are pointing in the same direction, their dot product is positive. This seems reasonable enough: if you took the dot product of a vector with itself, it would be the squared length of the vector. The opposite case also seems reasonable: when the vectors point away from each other, the result will be negative. And the point where they’re exactly perpendicular to each other? There’s nothing in common between the vectors, so the dot product returns 0!

The dot product is proportionate to how closely the vectors are pointing in the same direction. This sounds valuable when we think about applying it in our games. “If the bad guy’s facing away from the player, wander around. If they’re facing the player, ATTACK!”



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.